package com.ideaaedi.springcloud.jd.commonspring.filter;

import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import com.ideaaedi.springcloud.jd.commonds.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * traceId
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.A
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TraceIdFilter implements Filter{
    
    @Override
    public void init(FilterConfig filterConfig) {
    
    }
    
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        try {
            String traceId;
            if ((request instanceof HttpServletRequest)) {
                HttpServletRequest httpServletRequest = (HttpServletRequest)request;
                traceId = CommonUtil.getTraceId(httpServletRequest.getRequestURI(), httpServletRequest.getHeader(BaseConstant.TRACE_ID));
            } else {
                traceId = CommonUtil.getTraceId(null, null);
            }
            putTraceId(traceId);
            chain.doFilter(request, response);
        } finally {
            clearTraceId();
        }
    }
    
    @Override
    public void destroy() {
    
    }
    
    /**
     * 放置traceId
     */
    public static void putTraceId(String traceId) {
        try {
            MDC.put(BaseConstant.TRACE_ID, traceId);
        } catch (Exception e) {
            log.warn("putTraceId error. " + e.getMessage());
            // ignore
        }
    }
    
    /**
     * 清除traceId
     */
    public static void clearTraceId() {
        try {
            MDC.remove(BaseConstant.TRACE_ID);
        } catch (Exception e) {
            log.warn("clearTraceId error. " + e.getMessage());
            // ignore
        }
    }
}
